package com.icrazy.platform.action;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.icrazy.platform.exception.DaoException;
import com.icrazy.platform.exception.ServiceException;
import com.icrazy.platform.util.CallBack;
import com.icrazy.platform.util.Json;
import com.icrazy.platform.util.Struts2Utils;
import com.icrazy.platform.util.Ts;
import com.opensymphony.xwork2.ActionSupport;

/**
 * Struts2基础类
 * 
 * @author xiaofeng
 * @version 2012-3-15
 */
@SuppressWarnings({ "rawtypes", "serial" })
public class PlatformAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {

	public static final Log log = LogFactory.getLog(PlatformAction.class);

	protected Map session;
	protected HttpServletRequest req;
	protected HttpServletResponse rep;
	protected Map<String, Object> map = new ConcurrentHashMap<String, Object>();
	protected String rs;

	public void setServletResponse(HttpServletResponse rep) {
		this.rep = rep;
	}

	public void setServletRequest(HttpServletRequest req) {
		this.req = req;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	/**
	 * 发送JSON信息
	 * 
	 * @param obj
	 *            对象
	 */
	public void send(Object obj) {
		String str = Json.toJson(obj);
		Struts2Utils.renderHtml(str);
	}

	/**
	 * 发送字符串信息
	 * 
	 * @param str
	 *            字符串
	 */
	public void send(String str) {
		Struts2Utils.renderHtml(str);
	}

	/**
	 * 返回JSON字符串
	 * 
	 * @param cb
	 */
	public void json(CallBack cb) {
		try {
			cb.run();
			send(map);
		} catch (DaoException e) {

		} catch (ServiceException e) {

		} catch (Exception e) {
			String code = "";
			String message = e.getMessage();
			if (Ts.hv(message)) {
				if (message.contains("ORA-00936")) {
					code = "936";
				} else if (message.contains("ORA-00984")) {
					code = "984";
				} else if (message.contains("by zero")) {
					code = "1001";
				}
			}
			map.put("sts", code);
			send(map);
		}
	}

	/**
	 * 返回JSON字符串
	 * 
	 * @param cb
	 */
	public void text(CallBack cb) {
		try {
			cb.run();
			send(rs);
		} catch (Exception e) {
			String code = "";
			String message = e.getMessage();
			if (Ts.hv(message)) {
				if (message.contains("ORA-00936")) {
					code = "936";
				} else if (message.contains("ORA-00984")) {
					code = "984";
				} else if (message.contains("by zero")) {
					code = "1001";
				} else {
					code = "1000";
				}
			}
			map.put("sts", code);
			send(map);
		}
	}
}
